(function (window, $, undefined) {
  'use strict';

  var dictData = {
    city_id: {},
    auto_type: {},
    status: {}
  }

  var curCfg = ''
  var reservData = {}
  var durationData = {}
  var $formDurationDetail = $('#durationDetail')
  var $formDuration = $('#form-list-detail')
  var $layerDuration = $('#layer-list-detail')

  main(function () {

    var $tableReservList = $('#table-reservList');
    util.jqGrid($tableReservList, {
      url: ajaxURL.SCHEDULE + '/v1/reserve/config/listDetail?orderBy=city_id,auto_type,begin_time',
      //datatype: 'json',
      autowidth: true,
      height: $(window).height() - 320,
      multiselect: true,
      multiboxonly: true,
      // shrinkToFit: false,
      loadComplete: function (res) {
        reservData = {};
        if (res && res.data) {
          $.each(res.data, function (_, item) {
            reservData[item.kid] = item;
          });
        }
      },
      colModel: [
        { name: 'kid', key: true, hidden: true },
        { name: 'reserve_cfg_id', hidden: true },
        { name: 'status', hidden: true },
        {
          label: '城市', name: 'city_id', width: 80, formatter: function (v, o, r) {
            return dictData.city_id[v] || '';
          }
        },
        {
          label: '车辆类型', name: 'auto_type', width: 150, formatter: function (v, o, r) {
            return dictData.auto_type[v] || '';
          }
        },
        {
          label: '使用时段', name: '_duration', width: 200, formatter: function (v, o, r) {
            return r.begin_time + ' - ' + r.end_time;
          }
        },
        { label: '上限订单量', name: 'quantity', width: 100 },
        {
          label: '参数状态', name: '_status', width: 80, formatter: function (v, o, r) {
            return dictData.status[r.status] || '';
          }
        }
      ],
      pager: '#pager-reservList'
    });

    var $searchCondition = $('.search-condition');

    // 表单搜索功能
    $('#btn-search').click(function () {
      var data = util.formData($searchCondition)

      $tableReservList.jqGrid('setGridParam', {  // 重新加载数据
        postData: data
      }).trigger("reloadGrid");
    })

    // 获取城市列表
    util.get(ajaxURL.ORGANIZATION + '/city/getCityList?pageNum=1&pageSize=99999', function (res) {
      util.selectHtml($('[name="city_id"]'), res.data, 'cityId', 'name', '请选择');
      $.each(res.data, function (_, item) {
        dictData.city_id[item.cityId] = item.name;
      });
      searchTable();
    });

    util.getDict('vehiclePurpose', 'vehiclePurpose').then(function (data) {
      util.selectHtml('[name="auto_type"]', data, 'value', 'name', '请选择');
      $.each(data, function (_, item) {
        dictData.auto_type[item.value] = item.name;
      });
    });

    util.getDict('status', 'status').then(function (data) {
      // util.selectHtml('[name="status"]', data, 'value', 'name', '请选择');
      $.each(data, function (_, item) {
        dictData.status[item.value] = item.name;
      });
    });

    function searchTable() {
      var data = util.formData('#form-search');
      util.searchGrid($tableReservList, data);
    }

    // 新增页面
    $('#btn-add').click(function () {

      $('#duration-save').removeClass('hide');
      $('#duration-edit').addClass('hide');
      $('#durationSettingForm').empty();
      util.resetForm($formDuration);
      $layerDuration.find(':input').removeAttr('disabled');
      util.layerOpen({
        title: '新增预约单上限',
        content: $layerDuration,
        area: ['1000px', '600px'],
        cancel: function (index) {
          layer.confirm('确定退出当前页面？', {
            btn: ['确定', '再想一想'],
            yes: function (idx) {
              layer.close(index);
              layer.close(idx);
            }
          });
          return false;
        }
      });
    });

    // 保存操作
    $('#duration-save').click(function () {

      var durationData = [];

      getDurationSetting(durationData);

      var data = util.formData($formDuration);
      data.detailList = durationData;

      var url = ajaxURL.SCHEDULE + '/v1/reserve/config/add';
      if ($validate.form()) {
        if ($durationSetting.find('.error').length > 0) {
          util.tip.warn('请输入正确时间段格式 hh:mm:ss')
          return false
        }
        if (data.detailList.length > 0 && data.detailList.length <= 24) {
          if (checkInterval(durationData, durationData.length, $durationSetting.find('input.nxtDay').prop('checked'))) {
            util.post(url, data, function (res) {
              layer.closeAll();
              util.tip.success('操作成功');
              $tableReservList.trigger('reloadGrid');
            });
          }
        } else if (data.detailList.length > 24) {
          util.tip.warn('时段设置过多（最多24段）')
        } else {
          util.tip.warn('请进行时段设置')
        }
      }

    });

    var durationNum = '';
    // 修改界面
    $('#btn-edit').click(util.oneCheck($tableReservList, function (id) {

      $layerDuration.find(':input[name="city_id"]').attr('disabled', 'disabled');
      $layerDuration.find(':input[name="auto_type"]').attr('disabled', 'disabled');
      $layerDuration.find(':input[name="status"]').removeAttr('disabled');

      $('#duration-save').addClass('hide');
      $('#duration-edit').removeClass('hide');

      var reserve_cfg_id = reservData[id].reserve_cfg_id;
      curCfg = reserve_cfg_id;
      util.resetForm($formDurationDetail);

      util.ajax(ajaxURL.SCHEDULE + '/v1/reserve/config/get', {
        kid: reserve_cfg_id
      }, 'GET', util.resCallback(function (res) {

        // 获取派单轮次数
        durationNum = res.data.detailList.length;

        var data = res.data;
        util.fillForm($formDuration, data);

        // 填充派单轮次数据
        loadDetailInfo(durationNum, res.data.detailList, 'durationSettingForm');
        util.layerOpen({
          title: '修改预约单上限',
          content: $layerDuration,
          area: ['1000px', '600px'],
          cancel: function (index) {
            layer.confirm('确定退出当前页面？', {
              btn: ['确定', '再想一想'],
              yes: function (idx) {
                layer.close(index);
                layer.close(idx);
              }
            });
            return false;
          }
        });
      }
      ));
    }))

    // 修改操作
    $('#duration-edit').click(function () {

      var durationData = [];
      getDurationSetting(durationData);

      var data = util.formData($formDuration);
      data.detailList = durationData;
      data.kid = curCfg;

      var url = ajaxURL.SCHEDULE + '/v1/reserve/config/update';
      if ($validate.form()) {
        if ($durationSetting.find('.error').length > 0) {
          util.tip.warn('请输入正确的格式，时间为 hh:mm:ss，数量为非负整数')
          return false
        }
        if (data.detailList.length > 0 && data.detailList.length <= 24) {
          if (checkInterval(durationData, durationData.length, $durationSetting.find('input.nxtDay').prop('checked'))) {
            util.post(url, data,function (res) {
              layer.closeAll();
              util.tip.success('操作成功');
              $tableReservList.trigger('reloadGrid');
            });
          }
        } else if (data.detailList.length > 24) {
          util.tip.warn('时段设置过多（最多24段）')
        } else {
          util.tip.warn('请进行时段设置')
        }
      }
    });

    // 检查时段设置所填元素是否满足条件
    function checkInterval(data, length, isNxtDay) {
      var intervalData = []
      var i = 0;

      for (i = 0; i < length; i++) {
        if (data[i].begin_time && data[i].end_time && data[i].quantity) {
          intervalData.push({
            begin: carc(data[i].begin_time),
            end: carc(data[i].end_time)
          });
        } else {
          util.tip.warn('请将数据填写完整！');
          return false;
        }
      }

      intervalData.sort(function (a, b) {
        return a.begin > b.begin ? 1 : -1;
      })

      if (isNxtDay) {
        if (intervalData[length - 1].end > intervalData[0].begin) {
          util.tip.warn('选定次日情况下，结束时间不能大于最早的开始时间');
          return false
        }
        if (intervalData[length - 1].end > intervalData[length - 1].begin) {
          util.tip.warn('选定次日情况下，结束时间不能大于开始时间');
          return false
        }
        // 给最后一个时间追加一整天的秒数，用于做后面的判断
        intervalData[length - 1].end += 24 * 3600;
      }

      for (i = 0; i < length; i++) {
        if (intervalData[i].begin >= intervalData[i].end) {
          util.tip.warn('时段结束时间必须大于开始时间');
          return false;
        }
      }
      for (i = 1; i < length; i++) {
        if (intervalData[i].begin < intervalData[i - 1].end) {
          util.tip.warn('时段不能出现交叉和重叠，请调整后再进行提交');
          return false;
        }
      }

      return true
    }

    // 讲填写的时段转化为数值
    function carc(time) {
      var timeList = time.split(":")
      var timeVal = timeList[0] * 3600 + timeList[1] * 60 + timeList[2] * 1
      return timeVal
    }

    var $durationSetting = $('#durationSettingForm')
    // 页面上加载新的时段设置
    $('#btn-addDuration').click(function () {
      var ret = ''
      var n = $durationSetting.children().length

      if (n === 24) {
        util.tip.warn('时段设置已超过上限24')
        return false
      }

      // 判断最后一项时段是否勾选次日
      var hasNxtDay = false
      if ($durationSetting.find('input.nxtDay').length > 0) {
        hasNxtDay = true
      }
      ret += '<div class="row form-row form-row-sm"><div class="col-xs-12"><div class="form-text"> 时段 </div><div class="form-container form-inline"><input name="begin_time' + n + '" class="begin_time form-control" placeholder="00:00:00"><span class="text marginR10"> 至</span><input name="end_time' + n + '" class="marginR10 form-control end_time" placeholder="00:00:00"><span class="text">数量：</span><input name="quantity' + n + '" class="form-control marginR10 quantity">' + /*(hasNxtDay ? '' : '<label class="marginR10"><input type="checkbox" class="marginR10 nxtDay">次日</label>') + */'<button class="btn btn-default btn-del" type="button">删除</button></div></div></div>';
      if (n === 0) {
        $durationSetting.append(ret)
      } else {
        $durationSetting.children().last()[hasNxtDay ? 'before' : 'after'](ret)
      }
    })

    // 收集页面上的时段设置数据
    function getDurationSetting(data) {
      $formDurationDetail.find('#durationSettingForm').children().each(function () {
        var $this = $(this)
        data.push({
          begin_time: $this.find('input.begin_time').val(),
          end_time: $this.find('input.end_time').val(),
          quantity: $this.find('input.quantity').val(),
          status: ''
        })
      })
    }

    // 页面上渲染后台传入的时段设置数据
    function loadDetailInfo(n, data, form) {
      var ret = '';
      for (var i = 0; i < n; i++) {
        ret += '<div class="row form-row form-row-sm"><div class="col-xs-12"><div class="form-text"> 时段 </div><div class="form-container form-inline"><input name="begin_time' + i + '" class="begin_time form-control" value="' + data[i].begin_time + '"><span class="text marginR10"> 至</span><input name="end_time' + i + '" class="marginR10 form-control end_time" value="' + data[i].end_time + '"><span class="text">数量：</span><input name="quantity' + i + '" class="form-control marginR10 quantity" value="' + data[i].quantity + '">' + /*(i === (n - 1) ? '<label class="marginR10"><input type="checkbox" class="marginR10 nxtDay">次日</label>' : '') + */'<button class="btn btn-default btn-del" type="button">删除</button></div></div></div>'
      }
      $('#durationSettingForm').html(ret);
      for (var i = 0; i < n; i++) {
        $("select[name=status" + i + "]").val(data[i].status);
      }
      if (carc(data[n - 1].end_time) < carc(data[n - 1].begin_time)) {
        $durationSetting.find('input.nxtDay').prop('checked', true);
      }
    }

    // 校验时段格式
    $durationSetting.on('keyup change', '.begin_time, .end_time', function () {
      var $this = $(this)
      var val = $this.val()
      if (/^(2[0-3]|[01]\d):[0-5]\d:[0-5]\d$/.test(val)) {
        $this.removeClass('error')
      } else {
        $this.addClass('error')
      }
    })

    // 校验运力数格式
    $durationSetting.on('keyup change', '.quantity', function () {
      var $this = $(this)
      var val = $this.val()
      if (/^[1-9]\d{0,4}?$/.test(val)) {
        $this.removeClass('error')
      } else {
        $this.addClass('error')
      }
    })

    // 验证表格规则
    var $validate = $formDuration.validate({
      rules: {
        city_id: { required: true },
        auto_type: { required: true },
        status: { required: true }
      },
      messages: {
        city_id: { required: '请选择城市' },
        auto_type: { required: '请选择用车类型' },
        status: { required: '请选择记录状态' }
      },
      errorPlacement: function (error, element) { //错误信息位置设置方法
        error.appendTo(element.parents('.form-container')); //这里的element是录入数据的对象
      },
    });

    // 删除时段
    $('#durationSettingForm').on('click', '.btn-del', function () {
      var $this = $(this);
      $this.parent().parent().parent().remove();
    });

    // 启用
    $('#btn-startUp').click(function () {
      util.tip.warn('启用操作...');
    });

    // 禁用
    $('#btn-ban').click(function () {
      util.tip.warn('禁用操作...');
    });

    // 删除
    $('#btn-del').click(util.oneCheck($tableReservList, function (id, data) {
      if (+data.status === 101) {
        return util.tip.warn('启用状态的数据不能直接删除！');
      }
      layer.confirm('确定要删除？该操作会将对应城市和车型下的所有配置全部删除，请谨慎操作！', function () {
        util.post(ajaxURL.SCHEDULE + '/v1/reserve/config/remove?kid=' + data.reserve_cfg_id, function (res) {
          util.tip.success('删除成功');
          $tableReservList.trigger('reloadGrid');
        });
      });
    }));


  });
})(window, jQuery);
